package com.example.moilapp.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.example.moilapp.Moil_DO;
import com.example.moilapp.Moil_Pending_Tasks;
import com.example.moilapp.R;
import com.example.moilapp.adapter.Moil_Pending_Task_Adapter;

public class Moil_Pendingtask_Service  extends AsyncTask<String, Void, String> {

	private ProgressDialog progdialod;
	private Activity activity;
	private Context context;
	
	Moil_Pending_Task_Adapter listAdapter;
	
	//List<String> listDataHeader_jobid = new ArrayList<String>();
	
    ExpandableListView expListView;
    List<String> listDataHeader = new ArrayList<String>();
    HashMap<String, List<String>> listDataChild = new HashMap<String, List<String>>();
    
    HashMap<String, List<String> > hmSerial = new HashMap<String, List<String>>();
    
    HashMap<String, List<String> > hm_Deli_pickup = new HashMap<String, List<String>>();
    
	private ExpandableListView ExLstVw;
	
	private String UID;
	// connection establish timeout (timeoutConnection)
	private int timeoutConnection = 5000;
	// socket timeout (timeoutSocket) 
	private int timeoutSocket = 45000;
	
	private static byte[] buff =new byte[1024];
	private String retval="";
	
	private int[] app_ids;
	private String[] picArr;
	
	String pass_job_id="";
	String pass_TW_Address = "";
	
	String passPickupAddr="";
	String passDeliverAddr="";

	JSONArray jArray;
	private static final String SOAP_ACTION = "http://tempuri.org/Get3DaysPendingTaskByUser";

	//http://t2a1.cloudapp.net/TrafficWorkflow/TraficWorkflowWebService.asmx
	
    private static final String METHOD_NAME = "Get3DaysPendingTaskByUser";

    private static final String NAMESPACE = "http://tempuri.org/";
    private static final String URL = "http://t2a1.cloudapp.net/TrafficWorkflow/TraficWorkflowWebService.asmx";
	private static final String TAG = null;
	
	public Moil_Pendingtask_Service(Activity activity,String UID) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.UID = UID;
		Log.e("Service Pass UID", UID);
	}
	
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progdialod = ProgressDialog.show(this.activity, "Search", "Updating",true,false);
	}
	
	
	@Override
	protected String doInBackground(String... urls) {
		
		 try {

	            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
	            
	            String todayStr = getToday();

	            request.addProperty("UID", UID);
	            request.addProperty("today", todayStr);
	            
	            Log.e("Today Day Comes Here :", todayStr);

	            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	            envelope.dotNet=true;
	            envelope.setOutputSoapObject(request);

	            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
	            androidHttpTransport.call(SOAP_ACTION, envelope);
	            
	            SoapPrimitive resultSoapPrimitive;
	            resultSoapPrimitive = (SoapPrimitive) envelope.getResponse();
	                
	            String result = resultSoapPrimitive.toString();

	            retval = result;
	            
	            Log.d("return", retval);
	            
	            return retval;
	           
	        } catch (Exception e) {
	            
	       }
		 return retval;
		
	}
	
	@Override
	protected void onPostExecute(String result) {

		Log.d("Post Exec", "POST EXEC");
		
		
		
		/*Toast toast = Toast.makeText(activity, result, Toast.LENGTH_SHORT);
		toast.show();*/
		
		Log.d("Post tt", result);
		progdialod.dismiss();

		Log.d("Post Exec", result);
		
		try {
			
			jArray = new JSONArray(result);
			
			JSONArray jArraysrtd = sortJsonArray(jArray);
			
			
			List<Integer> numberLst = new ArrayList<Integer>();
			List<String> DateLst = new ArrayList<String>();
			
			int prv_serInt=0;
			
			picArr = new String[jArraysrtd.length()];

			for (int i = 0; i < jArraysrtd.length(); i++) {
				
			JSONObject element01 = jArraysrtd.getJSONObject(i);

			JSONObject element02 = element01.getJSONObject("TWTaskList");

			
			
			String serial_no = element02.getString("serial_no");
			String job_date = element02.getString("job_date");
			String job_id = element02.getString("job_id");
			int pickup_delivery = element02.getInt("pickup_delivery");
			String pic = element02.getString("pic");
			//pickup_delivery
			
			picArr[i] = pic;
			
			String[] split_serial = serial_no.split(".");
			
			//String first = split_serial[0];
			
			double ser = Double.parseDouble(serial_no);
			
			int serInt = (int) Math.round(ser);
			
			//int serInt_1 = Integer.parseInt(first);
			
			String convertd_date = convertDate(job_date);

			String TWClient = element01.getString("TWClient");
			
			String TWVassel = element01.getString("TWVassel");
			
			String TWAddress = element01.getString("TWAddress");

			//TWAddress
			
			Log.v("pickup_delivery", ""+pickup_delivery);
			
			//Check For What Kind Of Address

			pass_job_id = job_id;
			pass_TW_Address = TWAddress;
			
			/*for (HashMap.Entry<String,List<String>> entry : hmSerial.entrySet()) {
				  String key = entry.getKey();
				  Log.e("keys", key);
			}*/
			
			if(hm_Deli_pickup.size()==0 ){
				List<String> lstStuff = new ArrayList<String>();
				lstStuff.add(pickup_delivery+"/"+pass_TW_Address+"/"+serial_no+"/"+convertStarndardDate(job_date)+"/"+pic+"/"+job_id);
				
				hm_Deli_pickup.put(""+serInt+"@"+serial_no, lstStuff);
				
				Log.e("hm_Deli_pickup.size zero get", ""+serInt+"@"+serial_no);
			}else{
				
				if(!hm_Deli_pickup.containsKey(""+serInt+"@"+serial_no)){
					List<String> lstStuff = new ArrayList<String>();
					lstStuff.add(pickup_delivery+"/"+pass_TW_Address+"/"+serial_no+"/"+convertStarndardDate(job_date)+"/"+pic+"/"+job_id);
					
					Log.e("has Key hm_Deli_pickup", ""+hm_Deli_pickup.get(""+serInt+"@"+serial_no));
					
					hm_Deli_pickup.put(""+serInt+"@"+serial_no, lstStuff);
				}else{
					Log.e("hm_Deli_pickup.size IN", ""+hm_Deli_pickup.size());
					hm_Deli_pickup.get(""+serInt+"@"+serial_no).add(hm_Deli_pickup.get(""+serInt+"@"+serial_no).size(),pickup_delivery+"/"+pass_TW_Address+"/"+serial_no+"/"+convertStarndardDate(job_date)+"/"+pic+"/"+job_id);
				}
		
			}
			

			if(hmSerial.size()==0 ){
				List<String> lstStuff = new ArrayList<String>();
				lstStuff.add(job_id+"~"+serial_no+"~"+convertStarndardDate(job_date)+"~"+pickup_delivery);
				
				hmSerial.put(""+serInt+"@"+serial_no, lstStuff);

				Log.e("hmSerial.size get", ""+hmSerial.get(""+serInt+"@"+serial_no));
			}else{
				
				if(!hmSerial.containsKey(""+serInt+"@"+serial_no)){
					List<String> lstStuff = new ArrayList<String>();
					lstStuff.add(job_id+"~"+serial_no+"~"+convertStarndardDate(job_date)+"~"+pickup_delivery);
					
					hmSerial.put(""+serInt+"@"+serial_no, lstStuff);
				}else{
					Log.e("hmSerial.size", ""+hmSerial.size());
					hmSerial.get(""+serInt+"@"+serial_no).add(hmSerial.get(""+serInt+"@"+serial_no).size(),job_id+"~"+serial_no+"~"+convertStarndardDate(job_date)+"~"+pickup_delivery);
				}
		
			}

			if(numberLst.contains(serInt)){

			}else{
				
				numberLst.add(serInt);
				
				if(!containsDate(DateLst,convertd_date.replace(" ", ""))){
					
					DateLst.add(convertd_date.replace(" ", ""));
					
					listDataHeader.add(convertd_date);
					List<String> substuff = new ArrayList<String>();
					Log.e("serInt_pass", ""+serInt);
					Log.e("TWClient", ""+TWClient);
					Log.e("TWVassel", ""+TWVassel);
					substuff.add(serInt+" - "+TWClient+" \""+TWVassel+"\"");
					listDataChild.put(convertd_date, substuff);
					
				}else{
					listDataChild.get(convertd_date).add(listDataChild.get(convertd_date).size(),serInt+" - "+TWClient+" \""+TWVassel+"\"");
				}
				
				
			}

			/*for (Map.Entry<String,List<String>> entry : hm_Deli_pickup.entrySet()) {
		    	  Log.v("bfr loop:key", entry.getKey());
		    	  Log.v("bfr loop:value", ""+entry.getValue());
		    }*/
			
			}
			
			Log.v("hm_Deli_pickup.size", ""+hm_Deli_pickup.size());
		    Log.v("hmSerial.size", ""+hmSerial.size());
		    
		    for (Map.Entry<String,List<String>> entry : hm_Deli_pickup.entrySet()) {
		    	  Log.v("hm_Deli_pickup entry.getKey():key", entry.getKey());
		    	  Log.v("hm_Deli_pickup entry.getKey():value", ""+entry.getValue());
		    }
		
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		//PRIYAN
		
		expListView = (ExpandableListView) activity.findViewById(R.id.list);
		
		listAdapter = new Moil_Pending_Task_Adapter(context, listDataHeader, listDataChild,expListView);

	    expListView.setAdapter(listAdapter);
	    
	    listAdapter.notifyDataSetChanged();
	    
	    //Collections.sort(listDataHeader);
	     
	    int count = listAdapter.getGroupCount();
	     
	    for (int position = 1; position <= count; position++)
	    	 expListView.expandGroup(position - 1);
	    
	    expListView.setOnChildClickListener(new OnChildClickListener() {
	    	 
            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {
                
                Toast.makeText(
                		context,
                        listDataHeader.get(groupPosition)
                                + " : "
                                + listDataChild.get(
                                        listDataHeader.get(groupPosition)).get(
                                        childPosition), Toast.LENGTH_SHORT)
                        .show();
                
                
                final Intent intent = new Intent(activity, Moil_DO.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Bundle bundle = new Bundle();
				bundle.putString("pass_date", listDataHeader.get(groupPosition)); 
				bundle.putString("pic",picArr[groupPosition]);
				
				String completeTask = listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition);
				
				String[] spltStr = completeTask.split("\"");
				
				bundle.putString("pass_vassel", spltStr[1]);
			    
				spltStr[1] = "";
				
			    String AdjMessage = TextUtils.join("",spltStr);
			    
			    String[] dashStr = completeTask.split("-");
				
			    String Serialindex = dashStr[0];
			    
			    String Serialindex_dropspace = Serialindex.replace(" ", "");
			    
			    //String[] asArrayFromHashJobid = hmSerial.get(Serialindex_dropspace).toArray(new String[hmSerial.get(Serialindex_dropspace).size()]);
			    
			    List<String> strwithserial = new ArrayList<String>();
			    
			    for (Map.Entry<String,List<String>> entry : hmSerial.entrySet()) {
			    	  String[] first_second = entry.getKey().split("@");
			    	  
			    	  if(first_second[0].equals(Serialindex_dropspace)){
			    		  strwithserial.add(entry.getKey());
			    	  }
			    }
			    
			    List<String> fullList = new ArrayList<String>();
			    
			    for(int entrylp=0;entrylp<strwithserial.size();entrylp++){
			    	String[] asArrayDelPickupAddr = hmSerial.get(strwithserial.get(entrylp)).toArray(new String[hmSerial.get(strwithserial.get(entrylp)).size()]);
				    
				    for(int i=0;i<asArrayDelPickupAddr.length;i++){
				    	fullList.add(asArrayDelPickupAddr[i]);
				    	
				    } 
			    }
			    
			    String magicStr = "";
			    
			    for(int ij=0;ij<fullList.size();ij++){
			    	magicStr = magicStr+","+fullList.get(ij);
			    }
			    
			    
			    //Get Delivery and Pickup Address
			    
			    List<String> strSelectedPickups = new ArrayList<String>();
			    
			    for (Map.Entry<String,List<String>> entry : hm_Deli_pickup.entrySet()) {
			    	  String[] first_second = entry.getKey().split("@");
			    	  
			    	  Log.e("first_second[0]", first_second[0]);
			    	  Log.e("Serialindex_dropspace", Serialindex_dropspace);
			    	  
			    	  if(first_second[0].equals(Serialindex_dropspace)){
			    		  strSelectedPickups.add(entry.getKey());
			    		  //Log.e("EqUALED", "EqUALED");
			    	  }
			    }
			    
			    List<String> alldatalSelectedPickups = new ArrayList<String>();
			    
			    Log.e("hm_Deli_pickup size", ""+hm_Deli_pickup.size());
			    
			    for(int entrylp=0;entrylp<strSelectedPickups.size();entrylp++){
			    	String[] asArrayDelPickupAddr = hm_Deli_pickup.get(strSelectedPickups.get(entrylp)).toArray(new String[hm_Deli_pickup.get(strSelectedPickups.get(entrylp)).size()]);
				    
				    for(int i=0;i<asArrayDelPickupAddr.length;i++){
				    	alldatalSelectedPickups.add(asArrayDelPickupAddr[i]);
				    	String[] StrinpickuporDelivery = asArrayDelPickupAddr[i].split("-");
				    	if(StrinpickuporDelivery[0].equals("1")){
				    		passPickupAddr = StrinpickuporDelivery[1];
				    	}else if(StrinpickuporDelivery[0].equals("2")){
				    		passDeliverAddr = StrinpickuporDelivery[1];
				    	}
				    } 
			    }
			    
			    String 	magicStr_Address = "";
			    
			    for(int ij=0;ij<alldatalSelectedPickups.size();ij++){
			    	magicStr_Address = magicStr_Address+"~"+alldatalSelectedPickups.get(ij);
			    }
			    
			    Log.e("magicStr_Address", magicStr_Address);
			    Log.e("magicStr", magicStr);

				bundle.putString("pass_title", AdjMessage);
				bundle.putString("job_id",magicStr);
				bundle.putString("pass_pickup_addr", passPickupAddr);
				bundle.putString("pass_delivery_addr", passDeliverAddr);
				bundle.putString("address_list", magicStr_Address);
				
				intent.putExtras(bundle);
				context.startActivity(intent);
                
                return false;
            }
        });
	    
	    expListView.setOnGroupClickListener(new OnGroupClickListener() {
	    	  @Override
	    	  public boolean onGroupClick(ExpandableListView parent, View v,
	    	                              int groupPosition, long id) { 
	    	    return true;
	    	  }
	    	});
	    
		
		//PRIYAN

		
		/*final Intent intent = new Intent(activity, Moil_DO.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Bundle bundle = new Bundle();
				
		bundle.putString("job_id", pass_job_id);  
				
		intent.putExtras(bundle);
		context.startActivity(intent);*/

		
	}
	
	private String getToday(){
		
		Calendar c = Calendar.getInstance();
		System.out.println("Current time => " + c.getTime());

		//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String formattedDate = df.format(c.getTime());
		
		return formattedDate;
	}
	
	private String convertDate(String inDate){

		SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 
		Date dateObj=null;;
		try {
			dateObj = curFormater.parse(inDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		SimpleDateFormat postFormater = new SimpleDateFormat("yyyy MMM dd"); 

		String newDateStr = postFormater.format(dateObj); 

		return newDateStr;
	}
	
	private String convertStarndardDate(String inDate){

		SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 
		Date dateObj=null;;
		try {
			dateObj = curFormater.parse(inDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd"); 

		String newDateStr = postFormater.format(dateObj); 

		return newDateStr;
	}
	
	public static JSONArray sortJsonArray(JSONArray array) {
	    List<JSONObject> jsons = new ArrayList<JSONObject>();
	    for (int i = 0; i < array.length(); i++) {
	        try {
				jsons.add(array.getJSONObject(i));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	    Collections.sort(jsons, new Comparator<JSONObject>() {
	        @Override
	        public int compare(JSONObject lhs, JSONObject rhs) {
	            String lid="";
	            String rid="";
				try {
					JSONObject elementlhs = lhs.getJSONObject("TWTaskList");
					lid = elementlhs.getString("job_date");
					
					JSONObject elementrhs = rhs.getJSONObject("TWTaskList");
					rid = elementrhs.getString("job_date");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            
	            // Here you could parse string id to integer and then compare.
	            return lid.compareTo(rid);
	        }
	    });
	    return new JSONArray(jsons);
	}
	
	public boolean containsDate(List<String> lst,String dateStr){
		
		String search = dateStr;
		for(String str: lst) {
		    if(str.trim().contains(search))
		       return true;
		}
		return false;
	}

}
